package cn.gqr.service.Impl;

import cn.gqr.entity.Largefile;
import cn.gqr.entity.User;
import cn.gqr.entity.UserOrdInfo;
import cn.gqr.mapper.UserMapper;
import cn.gqr.service.HotService;
import cn.gqr.service.UserService;
import cn.gqr.tool.GetUser;
import cn.gqr.tool.RespJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    HotService hotService;


    @Override
    public int updatePwd(String pwd, int uid) {
        PasswordEncoder pe = new BCryptPasswordEncoder();
        return userMapper.updatePwd(pe.encode(pwd), uid);
    }

    @Override
    @Transactional
    public String updateImg(int uid, MultipartFile file, Largefile largefile) {
        //添加图片返回uuid
        String uuid = hotService.filesUpload(largefile, file);
        //把uuid赋值给用户
        userMapper.updateImg(uuid,uid);
        //删除原来的头像
        hotService.delPic(((User)GetUser.getUser()).getImg());
        //返回一个uuid
        return uuid;
    }

    @Override
    public int updateInfo(String nickname, String phone, int uid) {
        return userMapper.updateInfo(nickname, phone, uid);
    }

    @Override
    public List<User> findAll(int start,int num) {
        return userMapper.findAll(start,num);
    }

    @Override
    @Transactional
    public Map<String,Object> addAdm(User user, MultipartFile file, Largefile largefile) {
        if(file==null){
            return RespJson.pack(200,"图片未上传",null);
        }
        //上传图片，返回图片的uuid
        String uuid = hotService.filesUpload(largefile, file);
        //设置图片uuid
        user.setImg(uuid);
        PasswordEncoder pe = new BCryptPasswordEncoder();
        user.setPassword(pe.encode(user.getPassword()));
        System.out.println(user);
        userMapper.addAdm(user);
        return RespJson.pack(200,"添加成功..",null);
    }

    @Override
    public int resetPwd(int uid) {
        PasswordEncoder pe = new BCryptPasswordEncoder();
        return userMapper.resetPwd(pe.encode("111111"),uid);
    }

    @Override
    public int close(int uid) {
        return userMapper.close(uid);
    }

    @Override
    public User findById(int id) {
        return userMapper.findById(id);
    }

    @Override
    public UserOrdInfo findByIdUserInfo(int id) {
        return userMapper.findByIdUserInfo(id);
    }

    @Override
    public int userTotal() {
        return userMapper.userTotal();
    }
}
